package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 体检预约服务
 */
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderSettingDao orderSettingDao;
    @Autowired
    MemberDao memberDao;
    @Autowired
    OrderDao orderDao;

    //体检预约
    @Override
    public Result order(Map map) throws Exception {
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //2.检查预约日期是否已满
        int number = orderSetting.getNumber(); //可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if (reservations >= number) {
            //预约已满,不可预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //检查当前账户是否为会员,根据手机号判断
        String telephone = (String) map.get("telephone");//获取用户页面输入的手机号
        Member member = memberDao.findByTelephone(telephone);
        //防止重复提交
        if (member != null) {
            Integer memberId = member.getId();
            int setmealId = Integer.parseInt((String) map.get("setmealId"));
            Order order = new Order(memberId, date, null, null, setmealId);
            List<Order> list = orderDao.findByCondition(order);
            if (list != null && list.size() > 0) {
                //已经完成了预约，不能重复预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        }
        //如果电话不是会员就添加信息
        if (member == null) {
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);
        }

        //可预约,设定人数+1
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        //根据id查询预约信息,体检人信息,套餐信息
        Order order = new Order(member.getId(), date, (String) map.get("orderType"), Order.ORDERSTATUS_NO, Integer.parseInt((String) map.get("setmealId")));
        orderDao.add(order);
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());

    }

    @Override
    public Map findById(Integer id) throws Exception {
        Map map = orderDao.findById4Detail(id);
        if (map != null) {
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate", DateUtils.parseDate2String(orderDate));
        }
        return map;
    }


    /**
     * 预约管理模块
     *
     * @param order
     */


    //新增
    public void add(Order order) {
        orderDao.add(order);
    }

    //分页查询
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) throws Exception {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString(); //条件
        PageHelper.startPage(currentPage, pageSize);
        Page<Map<String, Object>> page = orderDao.findByConditionOrder(queryString);
        for (Map<String, Object> map : page) {
            if (map != null) {
                //分页 预约日期
                Date orderDate = (Date) map.get("orderDate");
                //日期转换-  String -> Date 工具类
                map.put("orderDate", DateUtils.parseDate2String(orderDate));
            }
        }
        System.out.println(page.getReasonable());

        return new PageResult(page.getTotal(), page.getResult());
    }

    //添加新检查项
    public void add(Map<String, Object> map, Integer[] setmealIds) throws Exception {
        String phoneNumber = (String) map.get("phoneNumber");
        String name = (String) map.get("name");
        String idCard = (String) map.get("idCard");
        String birthday = (String) map.get("birthday");
        String sex = (String) map.get("sex");
        String regTime = (String) map.get("regTime");

        Member member = new Member();
        member.setRegTime(DateUtils.parseString2Date(regTime));
        member.setPhoneNumber(phoneNumber);

        member.setName(name);
        member.setIdCard(idCard);
        member.setBirthday(DateUtils.parseString2Date(birthday));
        member.setSex(sex);
        memberDao.add(member);
        Integer memberId = member.getId();

        /**
         *  添加到 t_order表
         */
        String orderDate = (String) map.get("orderDate");
        for (Integer setmealId : setmealIds) {
            Order order = new Order();
            order.setSetmealId(setmealId);
            order.setOrderDate(DateUtils.parseString2Date(orderDate));
            order.setMemberId(memberId);
            order.setOrderStatus("未预约");
            order.setOrderType("电话预约");
            orderDao.add(order);
        }
    }

    //查询全部
    @Override
    public List<Map<String, Object>> findAll() {
        return orderDao.findAll();
    }

    //查询中间表id 确定预约
    @Override
    public void updateOrderStatus(Integer id) {
        String orderStatus = orderDao.findByOrderStatus(id);
        if (!orderStatus.equals("已预约")) {
            orderDao.updateOrderStatus(id);
            orderSettingDao.updateOrderSettingreservations(id);
        }
    }

    //查询中间表id 取消预约
    @Override
    public void updateOrderStatus2(Integer id) {
        String orderStatus = orderDao.findByOrderStatus(id);
        if (!orderStatus.equals("未预约")) {
            orderDao.updateOrderStatus2(id);
            orderSettingDao.updateOrderSettingreservations2(id);
        }
    }


    //多条确定预约
    @Override
    public void updateOrderStatusSelection(Integer[] ids) {
        for (Integer id : ids) {
            String orderStatus = orderDao.findByOrderStatus(id);
            if (!orderStatus.equals("已预约")) {
                orderDao.updateOrderStatus(id);
                orderSettingDao.updateOrderSettingreservations(id);
            }
        }
    }

    //多条取消预约
    @Override
    public void updateOrderStatusSelection2(Integer[] ids) {
        for (Integer id : ids) {
            String orderStatus = orderDao.findByOrderStatus(id);
            if (!orderStatus.equals("未预约")) {
                orderDao.updateOrderStatus2(id);
                orderSettingDao.updateOrderSettingreservations2(id);
            }
        }
    }
}


